package com.karry.yl.service.elder.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.karry.commons.base.impl.SuperServiceImpl;
import com.karry.yl.dao.elder.CheckOutRecordsMapper;
import com.karry.yl.domain.baseinfo.Bed;
import com.karry.yl.domain.baseinfo.Room;
import com.karry.yl.domain.elder.CheckInRecords;
import com.karry.yl.domain.elder.CheckOutRecords;
import com.karry.yl.domain.elder.Elderly;
import com.karry.yl.service.baseinfo.BedService;
import com.karry.yl.service.baseinfo.RoomService;
import com.karry.yl.service.elder.CheckInRecordsService;
import com.karry.yl.service.elder.CheckOutRecordsService;
import com.karry.yl.service.elder.ElderlyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service
public class CheckOutRecordsServiceImpl extends SuperServiceImpl<CheckOutRecordsMapper,CheckOutRecords> implements CheckOutRecordsService {
    @Autowired
    private ElderlyService elderlyService;
    @Autowired
    private RoomService roomService;
    @Autowired
    private BedService bedService;
    @Autowired
    private CheckInRecordsService checkInRecordsService;
    @Override
    @Transactional
    public void save(CheckOutRecords checkOutRecords, CheckInRecords checkInRecords) {
        baseMapper.insert(checkOutRecords);
        Elderly elderly = elderlyService.selectOne(new EntityWrapper<Elderly>().eq("id", checkOutRecords.getElderlyId()).eq("orgId", checkOutRecords.getOrgId()).eq("deleted",false));
        elderly.setCheckedIn(false);
//        elderly.setOrgId(Elderly.ORG_ID_NONE); //将老人从机构脱离
        elderly.setLeaveDate(new Date());
        elderlyService.updateById(elderly);

        //更新入住床位的状态
        Bed bed = bedService.selectById(checkInRecords.getBedId());
        bed.setStatus(Bed.STATUS_KX);
        bedService.updateById(bed);
        //删除入住记录
        checkInRecordsService.deleteById(checkInRecords.getId());
        //检查房间是否满员
        Room room = roomService.selectById(bed.getRoomId());
        int count = bedService.countByRoomId(bed.getRoomId());
        if(count < room.getBedNum()){   //如果不满员，设置为不满员
            room.setStatus(Room.STATUS_KY);
            roomService.updateById(room);
        }
    }
}
